<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统信息管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理角色信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索与添加区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入角色名"
            v-model="param.keyword"
            class="input-with-select"
            clearable
            @clear="getRoleList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getRoleList()"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="roleList" border stripe>
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="description" label="描述"> </el-table-column>

        <el-table-column
          prop="createTime"
          :formatter="dateFormat"
          label="创建时间"
        >
        </el-table-column>

        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="removeRoleById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="param.pageNum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="param.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 主体区域 -->
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    return {
      param: {
        pageSize: 5,
        pageNum: 1,
        keyword: '',
      },
      roleList: [],
      ids: [],
      total: null,
      // 控制对话框出现
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        name: '',
        description: '',
      },
      editForm: {},
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
    }
  },
  mounted() {
    this.getRoleList()
  },
  methods: {
    getRoleList() {
      this.$http
        .get('role/list', { params: this.param })
        .then((result) => {
          this.roleList = result.data.list
          this.total = result.data.total
        })
        .catch((err) => {})
    },
    handleSizeChange(newSize) {
      this.param.pageSize = newSize
      this.getRoleList()
    },
    handleCurrentChange(newPageNum) {
      this.param.pageNum = newPageNum
      this.getRoleList()
    },
    // 删除角色
    async removeRoleById(id) {
      const confirmResult = await this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err) // 取消删除

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      this.ids.push(id)
      let data = new URLSearchParams()
      data.append('ids', this.ids)
      this.$http
        .get('role/delete', {
          params: {
            ids: data.get('ids'),
          },
        })
        .then((result) => {
          console.log(result)
          this.getRoleList()
        })
    },
    // 显示修改对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('role/roleInfo/' + id)
      this.editForm = res
    },
    // 修改角色
    editRole() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('格式校验失败！')

        await this.$http.post('role/update/' + this.editForm.id, this.editForm)
        this.editDialogVisible = false
        this.getRoleList()
        this.$message.success('修改成功')
      })
    },
    dateFormat(date) {
      return moment(date.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    // 添加角色
    addRole() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('格式校验失败！')
        await this.$http.post('role/create', this.addForm)
        this.addDialogVisible = false
        this.getRoleList()
        this.$message.success('添加成功')
      })
    },
    addDialogClosed() {
      Object.assign(this.$data.addForm, this.$options.data().addForm)
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
  },
}
</script>

<style lang="less" scoped></style>
